package store.lunangangster.engine.impl.interceptor;

import store.lunangangster.engine.impl.Context;
import store.lunangangster.engine.impl.cmd.Command;

/**
 * 用于执行Command过程中的事务拦截器。该拦截器会在Command执行之前，为当前Command对应的CommandContext中
 * 添加{@link SessionListener}，用于监听{@link CommandContext#close()}方法。当CommandContext被
 * 关闭时，就说明命令执行完成。事务监听器就会根据命令执行的情况来进行commit或rollback。
 *
 * @author cwk
 * @version 1.0
 */
public class TransactionInterceptor implements CommandInterceptor {

  protected CommandInterceptor next;

  public TransactionInterceptor() {
  }

  public TransactionInterceptor(CommandInterceptor next) {
    this.next = next;
  }

  @Override
  public <T> T execute(Command<T> command) {
    CommandContext commandContext = Context.getCommandContext();
    try {
      commandContext.addSessionListener(new TransactionSessionCloseListener(commandContext));
      return next.execute(command);
    } finally {
    }
  }

  @Override
  public CommandInterceptor next() {
    return next;
  }

  @Override
  public void setNext(CommandInterceptor nextInterceptor) {
    next = nextInterceptor;
  }
}
